package com.d2.modules.system.permission.entity.vo;

import cn.hutool.core.util.StrUtil;
import com.d2.common.util.SpringContextUtils;
import com.d2.modules.system.permission.entity.Role;
import com.d2.modules.system.permission.entity.User;
import com.d2.modules.system.permission.mapper.IRoleMapper;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Data
public class LoginUser implements UserDetails {

    private Long id;
    private String username;
    private String password;
    private Collection<? extends GrantedAuthority> authorities;

    public LoginUser() {

    }

    // 写一个能直接使用user创建LoginUser的构造器
    public LoginUser(User user,Collection<? extends GrantedAuthority> authorities) {
        id = user.getId();
        username = user.getUsername();
        password = user.getPassword();
        this.authorities = authorities;
//        IRoleMapper roleMapper = SpringContextUtils.getBean(IRoleMapper.class);
//        List<Role> roles = roleMapper.queryRoleByUserId(id);
//        List<Long> collect = roles.stream().map(Role::getId).collect(Collectors.toList());
//        String join = StrUtil.join(",", collect);
//        if(StrUtil.isEmpty(join)){
//            join = "0";
//        }
//        authorities = Collections.singleton(new SimpleGrantedAuthority(join));
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
//        List<GrantedAuthority> authorities = new ArrayList<>();
//        IRoleMapper roleMapper = SpringContextUtils.getBean(IRoleMapper.class);
//        List<Role> roles = roleMapper.queryRoleByUserId(id);
//        for (Role role : roles) {
//            authorities.add(new SimpleGrantedAuthority(role.getCode()));
//        }
        return authorities;
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
